#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

void SLPrint(SList* ps)
{
	SList* cur = ps;
	while (cur != NULL) 
	{
		printf("%d->", cur->val);
		cur = cur->next;
	}
	printf("NULL\n");
}

SList* BuySLNode(SLDataType x)
{
	SList* newnode = (SList*)malloc(sizeof(SList));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	newnode->next = NULL;
	newnode->val = x;

	return newnode;
}

void SLPushBack(SList** ps, SLDataType x)
{
	SList* newnode = BuySLNode(x);
	if (ps == NULL) 
	{
		return;
	}
	else if (*ps == NULL)
	{
		*ps = newnode;
	}
	else 
	{
		SList* tail = *ps;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SLDestroy(SList* ps)
{
	SList* cur = ps;
	SList* next = NULL;
	while (cur != NULL) 
	{
		next = cur->next;
		free(cur);
		cur = next;
	}
}

void SLPopBack(SList** ps)
{
	if (*ps == NULL)
	{
		return;
	}
	else if((*ps)->next == NULL)
	{
		free(*ps);
		*ps = NULL;
	}
	else
	{
		SList* tail = *ps;
		SList* prev = NULL;
		while (tail->next != NULL)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		tail = NULL;
		prev->next = NULL;
	}
}

void SLPushFront(SList** ps, SLDataType x)
{
	SList* newnode = BuySLNode(x);
	newnode->next = *ps;
	*ps = newnode;
}

void SLPopFront(SList** ps)
{
	assert(*ps);
	SList* next = (*ps)->next;
	free(*ps);
	*ps = next;
}